package com.house.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Date;

@Component
public class AliYunOss {

    @Autowired
    private OSS ossClient;

    @Value("${aliyun.oss.bucket.name}")
    private String bucketName;

    // 100年不過期
    final long duration = 1000L * 60L * 60L * 24L * 365L * 100L;

    /**
     * 上传数据流
     *
     * @param is          数据输入流
     * @param path        文件在OSS上的存储路径(也就是OSS对象的key)
     * @param contentType 内容的mime-type
     * @return 返回已经映射的url字符串
     */

    public String upload(InputStream is,String path,
                         String contentType) throws URISyntaxException {
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType(contentType);
        ossClient.putObject(bucketName, path, is, metadata);
        URL url = generateUrl(path);
        URI uri = url.toURI();

        return uri.toString();
    }

    /**
     * 生成URL
     * @param key 上传资源的标识
     * @return 生成的URL
     */
    public URL generateUrl(String key){
        long time = System.currentTimeMillis()+duration;
        Date expiration = new Date(time);
        return ossClient.generatePresignedUrl(bucketName,key,expiration);
    }

}
